package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@Api(tags = "添加菜品分类")
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    DishService dishService;
    @PostMapping("")
    @ApiOperation("添加菜品")
    public Result<Dish> save(@RequestBody DishDTO DishDTO)
    {
        log.info("添加的菜品为{}",DishDTO);

        //删除缓存(添加菜品中有分类id)
        String key = "dish_" + DishDTO.getCategoryId();
        redisTemplate.delete(key);

        dishService.save(DishDTO);
        return Result.success();
    }
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO)
    {
        log.info("查询的菜品为{}",dishPageQueryDTO);
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }
    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result<Dish> delete(@RequestParam List<Long> ids)
    {
        log.info("当前删除id为{}",ids);
        //清除缓存
        shancuhuancun("dish_*");
        dishService.delete(ids);
        return  Result.success();

    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public  Result<DishVO> select(@PathVariable Long id)
    {
        log.info("查询的菜品id为{}",id);
        DishVO dishVO = dishService.select(id);
        return Result.success(dishVO);

    }
    @PutMapping
    @ApiOperation("修改菜品")
    public Result<Dish> update(@RequestBody DishVO dishVO)
    {
        log.info("修改的菜品为{}",dishVO.getName());
        //清除缓存
        shancuhuancun("dish_*");
        dishService.update(dishVO);
        return Result.success();
    }
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售")
    public Result<Dish> setstatus(@PathVariable Integer status,Long id)
    {
        dishService.setstatus(status,id);
        return Result.success();
    }
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId)
    {
        List<Dish> list = dishService.selectcateid(categoryId);
        return Result.success(list);
    }


    private void  shancuhuancun(String pattern)
    {
        Set<String> keys = redisTemplate.keys(pattern);
       if (keys!=null)
        redisTemplate.delete(keys);
    }



}
